//
//  simShopVisitPlanController.m
//  simens
//
//  Created by MICHAEL on 12-7-17.
//  Copyright (c) 2012年 yst. All rights reserved.
//

#import "simShopVisitPlanController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"
#import "simShopDetailController.h"

@interface simShopVisitPlanController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, ASIHTTPRequestDelegate>

@property (nonatomic,strong) UITableView *shopVisitPlanTableView;
@property (nonatomic,strong) UIAlertView* alertPlanVistDate;
@property (nonatomic,strong) UIAlertView* alertResult; 

@end

@implementation simShopVisitPlanController

@synthesize shopVisitPlanTableView=_shopVisitPlanTableView;
@synthesize homePageDelegate = _homePageDelegate;
@synthesize alertPlanVistDate = _alertPlanVistDate;
@synthesize alertResult = _alertResult;

NSArray* reportArray;
NSArray* tableViewArray;
NSString* planVistDate;
bool vistType;
NSString* response = @"false";

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.title=@"客户信息";
    
    self.shopVisitPlanTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, self.view.bounds.size.width, 
                                                                       self.view.bounds.size.height - 100)
                                                      style:UITableViewStylePlain];  
    
    [self.shopVisitPlanTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.shopVisitPlanTableView setDelegate:self];
    [self.shopVisitPlanTableView setDataSource:self];
    
    [self.view addSubview: self.shopVisitPlanTableView];
    
    if (vistType) {
        [self.shopVisitPlanTableView setEditing:NO animated:NO];
    } else {
        [self.shopVisitPlanTableView setEditing:YES animated:YES];
    }
    
    UISearchBar* searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 50)];
    searchBar.placeholder = @"输入客户名称查询";
    searchBar.delegate = self;
    searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    [self.view addSubview:searchBar];
    
    if (!vistType) {
        UIBarButtonItem* tempRight = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(submitVisitPlanInfo)];
        self.navigationItem.rightBarButtonItem = tempRight;
    }
    
}


-(void) viewWillAppear:(BOOL)animated {
    
    //xujiakun
}

-(void) submitVisitPlanInfo {
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提交计划" message: [NSString stringWithFormat:@"是否提交%@拜访计划？提交后计划将不能修改", planVistDate == nil ? @"" : planVistDate] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

-(void) alertView: (UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1){
        NSArray* selectedArray = [self.shopVisitPlanTableView indexPathsForSelectedRows];
        
        NSMutableString* text = [[NSMutableString alloc] init];
        
        // NSMutableArray* sub = [[NSMutableArray alloc] init];
        
        for (NSIndexPath* indexs in selectedArray) {
            NSUInteger index = [indexs indexAtPosition:[indexs length] - 1];
            NSDictionary* d = [tableViewArray objectAtIndex:index];
            
            //[sub addObject: [NSDictionary dictionaryWithObjectsAndKeys: [d objectForKey:@"custDetailId"], @"custDetailId", nil]];
            if ([text length] != 0) {
                [text appendString: @","];
            }
           // NSString* t = [d objectForKey:@"custDetailId"];
            [text appendString: [[d objectForKey:@"custDetailId"] stringValue]];
            
        }
                
        //NSMutableDictionary* submit = [[NSMutableDictionary alloc] init];
        //[submit setObject:sub forKey:@"siemensCustomer"];
        
        //UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" message:text delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        //[alert show];
                
        NSString* u=[NSString stringWithFormat:@"%@/%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],@"createVisitPlan"];
        NSURL *url = [NSURL URLWithString:u];
        
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
        
        [request addPostValue: [[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"] forKey:@"mobile"];
        [request addPostValue: [[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"] forKey:@"pwd"];
        [request addPostValue: text forKey:@"detailCustId"];
        [request addPostValue: planVistDate forKey:@"planVistDate"];
        
        if (!planVistDate) {
            self.alertPlanVistDate = [[UIAlertView alloc] initWithTitle:@"" message:@"请选择拜访日期" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [self.alertPlanVistDate show];
            return;
        }
        
        if ([text length] == 0) {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" message:@"请选择拜访客户" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        
        [self showMbprogress];
        
        [request setDelegate:self];
        [request start];
        
    } else if (buttonIndex == 0) {
        if ([response isEqualToString:@"true"]) {
            
            if (self.homePageDelegate) {
                [self.homePageDelegate changedToIndex:2];
            }
            return;
 //            simShopVisitCalendarController* shopvisitController = [[simShopVisitCalendarController alloc] init];
//            [self.navigationController pushViewController:shopvisitController animated:YES];
            // 菊花
        }
        
        if (actionSheet == self.alertPlanVistDate) {
            if (self.homePageDelegate) {
                [self.homePageDelegate changedToIndex:2];
            }
            return;
        }
        
        if (actionSheet == self.alertResult) {
            if ([response isEqualToString:@"3"]) {
                if (self.homePageDelegate) {
                    [self.homePageDelegate changedToIndex:2];
                }
                return;
            }
        }
    }
}

-(void) viewDidAppear:(BOOL)animated{
    [self showMbprogress];
    
    NSString *u =[NSString stringWithFormat:@"%@/getAllSiemensCustomers?mobile=%@&pwd=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"]];
    
    NSURL *url = [NSURL URLWithString: u];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    [request setDelegate:self];
    [request start];

}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (vistType) {
        return UITableViewCellAccessoryNone;
    } else {
        return UITableViewCellAccessoryCheckmark;
    }
}

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:YES animated:YES];
    
    NSMutableArray *array = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < reportArray.count; i++) {
        NSDictionary* temp = [reportArray objectAtIndex:i];
        NSString* s = [[temp objectForKey:@"custNameEn"] uppercaseString];
        
        NSRange range = [s rangeOfString: [searchBar.text uppercaseString]];
        
        if(searchBar.text.length == 0 || range.location != NSNotFound){
            [array addObject: temp];
        }
    }
    
    tableViewArray = array;
    
    [self.shopVisitPlanTableView reloadData];
    
}

-(void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.text = @"";
    [self searchBarSearchButtonClicked: searchBar];
    
}

-(void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(editingStyle == UITableViewCellEditingStyleInsert){

    }
}

//tableview行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [tableViewArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString* CellIdentifier = [NSString stringWithFormat:@"%d%d",indexPath.section, indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    
    for (UIView *v in [cell subviews]) {
        if ([v isKindOfClass:[UILabel class]] |
            [v isKindOfClass:[UIButton class]]) {
            [v removeFromSuperview];
        }
    }
    
    NSDictionary* temp = [tableViewArray objectAtIndex:indexPath.row];
    
    
    // 20 160
    // 50 180
    CGFloat x1;
    CGFloat x2;
    if(vistType) {
        x1 = 20;
        x2 = 190;
    } else{
        x1 = 50;
        x2 = 160;
    }
    
    UILabel* shopnameLabel = [[UILabel alloc] initWithFrame:CGRectMake(x1, 10, x2, 70)];
    [shopnameLabel setBackgroundColor:[UIColor clearColor]];
    [shopnameLabel setText: [temp objectForKey:@"custNameEn"]];
    shopnameLabel.font=[UIFont systemFontOfSize:16];
    shopnameLabel.numberOfLines=3;
    [cell addSubview:shopnameLabel];
    
    UILabel* visitNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 5, 100, 20)];
    [visitNumLabel setBackgroundColor:[UIColor clearColor]];
    [visitNumLabel setText:[NSString stringWithFormat:@"计划拜访次数：%@", [temp objectForKey:@"visitNum"]]];
    [visitNumLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
    visitNumLabel.font=[UIFont systemFontOfSize:12];
    [cell addSubview:visitNumLabel];
    
    UILabel* visitedNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 25, 100, 20)];
    [visitedNumLabel setBackgroundColor:[UIColor clearColor]];
    [visitedNumLabel setText:[NSString stringWithFormat:@"已经拜访次数：%@", [temp objectForKey:@"visitedNum"]]];
    [visitedNumLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
    visitedNumLabel.font=[UIFont systemFontOfSize:12];
    [cell addSubview:visitedNumLabel];
    
    UILabel* visitdateLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 45, 100, 35)];
    [visitdateLabel setBackgroundColor:[UIColor clearColor]];
    
    [visitdateLabel setText:[NSString stringWithFormat:@"上次拜访时间：%@", [temp objectForKey:@"visitDate"] == nil ? @"" : [[temp objectForKey:@"visitDate"] substringToIndex : 10 ]]];
    [visitdateLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
    visitdateLabel.font=[UIFont systemFontOfSize:12];
    visitdateLabel.numberOfLines=2;
    [cell addSubview:visitdateLabel];
    
    if (vistType) {
        UIImage* seletedImg = [UIImage imageNamed:@"tableviewcellSelected.png"];
        UIImageView *seletedImgView =[[UIImageView alloc] initWithImage:seletedImg];
        [cell setSelectedBackgroundView:seletedImgView];
    }
        
    UIImage* backImg = [UIImage imageNamed:@"tableviewcell.png"];
    UIImageView *backImgView =[[UIImageView alloc] initWithImage:backImg];
    [cell setBackgroundView:backImgView];
    
    return cell;
    
}

-(void) tableCellBeenPress:(int) index {
    if (vistType) {
        simShopDetailController* shopController = [[simShopDetailController alloc] init];

        NSDictionary* temp = [tableViewArray objectAtIndex:index];
        visitorItem *d=[[visitorItem alloc] init];
        NSString *date=[temp objectForKey:@"planVistDate"];
        d.visitDate=[date substringToIndex:10];
        d.contactName=[temp objectForKey:@"corporateDeputy"];
        if([[temp objectForKey:@"custPhone"] isKindOfClass:[NSString class]]==NO){
            d.contactPhone=[[temp objectForKey:@"custPhone"] stringValue];
        }else {
            d.contactPhone=[temp objectForKey:@"custPhone"];
        }
        d.custId=[temp objectForKey:@"custId"];
        d.custNameEn=[temp objectForKey:@"custNameEn"];
        
        [shopController setCustomerItem: d];
        
        [self.navigationController pushViewController:shopController animated:YES];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self tableCellBeenPress:indexPath.row];
}

-(void) setPlanVistDate:(NSString*) date {
    planVistDate = date;
}

-(void) setVistType:(bool) type {
    vistType = type;
}

//row高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    
    if (!error) {
        response = [request responseString];
        NSString *result;
        
        if ([response isEqualToString:@"2"]) {
            result = @"操作失败，请稍后再试";
        } else if ([response isEqualToString:@"1"]) {
            result = @"操作成功";
            response = @"true";
        } else if ([response isEqualToString:@"3"]) {
            result = @"操作失败，只能创建下周拜访计划";
        } else {
            response = @"false";
        }
        
        if (result != nil) {
            self.alertResult = [[UIAlertView alloc] initWithTitle:@"" message:result delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            
            [self hideMbProgress];
            [self.alertResult show];
            return;
        }
    }
    
    if (!error) {
        NSString *res = [request responseString];
        NSDictionary* dict = [res objectFromJSONString];
        reportArray = [dict objectForKey:@"siemensCustomer"];
        tableViewArray = reportArray;
        
        [self hideMbProgress];
    }
    
    [self.shopVisitPlanTableView reloadData];
    
}


- (void)requestFailed:(ASIHTTPRequest *)request {
    [self hideMbProgress];
}

@end
